package Server

import (
	//"fmt"
	"time"

	"git.oschina.net/yangdao/extlib/libInterface"
)

var mlog libInterface.ILog

func SetLog(setLog libInterface.ILog) {
	mlog = setLog
}
func Log(strTag string, values ...interface{}) {
	if mlog != nil {
		mlog.Log(strTag, values...)
	}
}

type ServerMessageHandler func(*Messge)

type IServer interface {
	PushMessage(*Messge)
	AddMessageHandler(uint16, ServerMessageHandler)
}

type Server struct {
	MessageQueue      chan *Messge
	MessageHandlerDic map[uint16]ServerMessageHandler
	UpdateSpeed       time.Duration
	UpdateFunc        func()
}

func NewServer() *Server {
	return &Server{
		MessageQueue:      make(chan *Messge, 10),
		MessageHandlerDic: make(map[uint16]ServerMessageHandler),
		UpdateSpeed:       1,
	}
}

func (this *Server) Run() {
	go this.Loop()
}

func (this *Server) Loop() {
	ticker := time.Tick(time.Millisecond * this.UpdateSpeed)
	for _ = range ticker {
		this.Update()
	}
}

func (this *Server) Update() {
	this.DispatchMessages()
	if this.UpdateFunc != nil {
		this.UpdateFunc()
	}
}

func (this *Server) DispatchMessages() {
	messageCount := len(this.MessageQueue)
	for i := 0; i < messageCount; i++ {
		msg := <-this.MessageQueue
		if fn, ok := this.MessageHandlerDic[msg.ID]; ok {
			fn(msg)
		} else {
			Log("Server,Warn", "收到了不存在的消息包", *msg)
		}
	}
}

func (this *Server) PushMessage(msg *Messge) {
	this.MessageQueue <- msg
}
